<template>
    <div class="app-view">
        <vxe-grid id="xGrid"
                  :loading="tableLoading"
                  ref="xGrid"
                  border
                  resizable
                  show-overflow
                  keep-source
                  highlight-hover-row
                  :height="tableH"
                  align="center"
                  :print-config="{}"
                  :import-config="{}"
                  :export-config="{}"
                  :custom-config="{ storage: true }"
                  :toolbar-config="tableToolbar"
                  :columns="tableColumn"
                  :seq-config="{startIndex: (tablePage.currentPage - 1) * tablePage.pageSize,}"
                  :pager-config="tablePage"
                  :data="tableData"
                  @page-change="handlePageChange"
                  @checkbox-change="checkboxChange"
                  @checkbox-all="checkboxAll">
            <template v-slot:toolbar_buttons>
                <div class="tableToolbar">
                    <div style="min-width:90px" class="tableToolbarText">数据包名称：</div>
                    <el-input v-model="searchName" size="small" style="margin-inline-start:8px;width:50%;" :placeholder="placeholder"
                              clearable @clear="getData(0)" @change="getData(0)" />
                    <vxe-button style="min-width:55px;margin-left:8px" status="primary" size="small" class="tableToolbarTextL searchButton"
                                @click="getData(0)">查询</vxe-button>
                    <el-tooltip content="上传文件" placement="bottom" effect="light">
                        <el-upload class="upload-demo"
                                   style="display:inline"
                                   ref="UpLoad"
                                   action="uploadUrl"
                                   :show-file-list="false"
                                   :auto-upload="false"
                                   :http-request="fileUpload"
                                   :on-change="selectFile"
                                   accept=".tdmpack">
                            <vxe-button style="margin-left:10px" size="small" status="primary">上传文件</vxe-button>
                        </el-upload>
                    </el-tooltip>
                </div>
            </template>
            <!--是否导入-->
            <template #isImport="{ row }">
                {{ row.isImport?'是':'否' }}
            </template>
            <template #operate="{ row }">
                <!--<el-link type="primary" class="elLinkBTN" @click="edit(row)">编辑</el-link>-->
                <el-link type="primary" :disabled="row.isImport" class="elLinkBTN" @click="starAnalysis(row)">导入</el-link>
                <!--<el-link type="primary" class="elLinkBTN" @click="downLoadFile(row)">下载</el-link>-->
                <el-link type="danger" class="elLinkBTN" @click="deleteDe(row)">删除</el-link>
            </template>
            <template v-slot:current_pageNum>
            </template>
        </vxe-grid>
        <vxe-modal v-model="showCreate" :title="formTitle" width="1100" resize destroy-on-close @close="dialogFormClose">
            <template #default>
                <vxe-form title-colon ref="myform" :data="formInfo" :loading="formLoading" :items="formItems" :rules="formRules">
                    <template #conName="{ data }">
                        <vxe-input v-model="conNameData.conName" readonly placeholder="请选择承制单位" @click="showSelectCon()" />
                    </template>
                </vxe-form>
                <div style="text-align:right">
                    <el-button @click="dialogFormClose">取 消</el-button>
                    <el-button type="primary" @click="save" class="searchButton">确 定</el-button>
                </div>
            </template>
        </vxe-modal>
        <vxe-modal v-model="showSelect" title="是否清除全部旧数据" width="500" resize destroy-on-close @close="dialogFormClose">
            <template #default>
                <el-radio-group v-model="optionType" size="mini" >
                    <el-radio v-for="item of delOption" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
                </el-radio-group>
                <div style="text-align:right">
                    <el-button @click="showSelect=false;type=false;">取 消</el-button>
                    <el-button type="primary" @click="starAnalysis()" class="searchButton">确 定</el-button>
                </div>
            </template>
        </vxe-modal>
    </div>
</template>
<script>
    import dataImportAPI from "../../request/DataManage/DataImportAPI.js";
    export default {
        components: {
        },
        name: 'GZFX',
        data() {
            return {
                tableH: window.innerHeight - topBarHeight - 80,
                tableLoading: false,
                delOption: [
                    { label: '是', value: true },
                    { label: '否', value: false },
                ],
                optionType: false,
                selectRow: {},
                showSelect:false,
                searchName: null,
                placeholder: "请输入",
                selectedItems: [],
                tableColumn: [
                    //{ field: 'checkbox', type: 'checkbox', title: '', visible: true, fixed: 'left', width: 70 },
                    { type: "seq", title: "序号", width: 70, fixed: "left" },
                    { field: "fileName", minWidth: 620, title: "文件名称" },
                    //{ field: "conName", minWidth: 120, title: "承制单位" },
                    //{ field: "ExportRepOffice", minWidth: 120, title: "导入代表室" },
                    { field: "importTime", minWidth: 120, title: "上传时间", formatter: ({ row }) => { return this.toDate(row.importTime) } },
                    { field: "isImport", minWidth: 80, title: "是否已导入", slots: { default: 'isImport' } },
                    { title: "操作", fixed: "right", width: 120, slots: { default: "operate" }, },
                ],
                tableToolbar: {
                    refresh: {
                        query: () => this.getData(0),
                    },
                    import: false,
                    export: false,
                    print: false,
                    custom: true,
                    slots: {
                        buttons: "toolbar_buttons",
                    },
                },
                tableData: [],
                tablePage: {
                    total: 0,
                    currentPage: 1,
                    pageSize: 50,
                    align: "right",
                    pageSizes: [50, 80],
                    layouts: [
                        "Sizes",
                        "PrevJump",
                        "PrevPage",
                        "JumpNumber",
                        "NextPage",
                        "NextJump",
                        "FullJump",
                        "Total",
                    ],
                    perfect: true,
                    slots: {
                        right: 'current_pageNum'
                    }
                },
                otherFaultShow: false,
                showCreate: false,
                formTitle: '',
                formInfo: {},
                formItems: [
                    { field: 'fileName', title: '图纸/资料名称', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'drawCode', title: '图纸/资料编号', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'conName', title: '承制单位', span: 12, slots: { default: 'conName' } },
                    { field: 'equipName', title: '设备名称', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'equipModel', title: '设备型号', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'storgeLoc', title: '存放地点', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                    { field: 'deployLoc', title: '部署船/地点', span: 12, itemRender: { name: '$input', props: { placeholder: '请输入' } } },
                ],
                formRules: {
                    //name: [{ required: true, message: '请填写船型名称' }],
                    //department: [{ required: true, message: '请选择船舶系列' }],
                },
                formLoading: false,
                conNameData: {},
                uploadUrl: '',
                loadingFullScreen: null,
            }
        },
        mounted() {
            this.getData();
            this.uploadUrl = requestURL + '/DataImportUpDnld/Upload/';
        },
        methods: {
            getData(type) {
                if (type === 0) {
                    this.tablePage.currentPage = 1;
                };
                var whereStr = " 1 = 1 ";

                if (!!this.searchName) {
                    whereStr += " and fileName like '%" + this.searchName.trim() + "%' ";
                }
                var data = {
                    pageIndex: this.tablePage.currentPage - 1,
                    pageSize: this.tablePage.pageSize,
                    selector: "",
                    where: whereStr,
                    sort: "importTime",
                    isAsc: false,
                    firstPK: 0,
                    lastPK: 0,
                    isDebugSQL: false,
                };
                this.tableLoading = true;
                dataImportAPI.getAllQuery(data).then(res => {
                    this.tableData = res.result;
                    this.tablePage.total = res.recordCount;
                    this.tableLoading = false;
                }).catch(err => {
                    this.tableLoading = false;
                });
            },

            dialogFormClose() {
                this.showCreate = false;
            },
            save() {
                this.$refs.myform.validate().then(suc => {
                    if (!suc) {
                        this.formLoading = true;
                        this.formInfo.conID = this.conNameData.conID;
                        this.formInfo.conName = this.conNameData.conName;
                        drawPaperAPI[this.formInfo.importID ? 'update' : 'create'](this.formInfo).then(res => {
                            if (!res) {
                                this.formLoading = false;
                                this.$message({ type: "warning", message: this.formInfo.importID ? "修改失败" : "创建失败" });
                                return;
                            } else {
                                this.$message({ type: "success", message: this.formInfo.importID ? "修改成功" : "创建成功" });
                                this.formLoading = false;
                                this.showCreate = false;
                                this.getData();
                            }
                        }).catch(err => {
                            this.formLoading = false;
                        })
                    }
                }).catch(err => {
                    console.log('err', err)
                })
            },
            createProject() {
                this.showCreate = true;
                this.formTitle = '新增';
                this.conNameData = {};
                this.formInfo = {
                    fileName: '',
                    drawCode: '',
                    repOffice: '',
                    conName: '',
                    equipName: '',
                    equipModel: '',
                    statusCode: null,
                    storgeLoc: '',
                    deployLoc: '',
                }
            },
            edit(row) {
                this.showCreate = true;
                this.formTitle = '编辑';
                this.formInfo = {};
                this.formLoading = true;
                dataImportAPI.getQueryByID(row.importID).then(res => {
                    this.formInfo = res;
                    this.formLoading = false;
                    this.conNameData = {
                        conID: res.conID,
                        conName: res.conName,
                    };
                }).catch(err => {
                    this.formLoading = false;
                });
            },
            deleteDe(row) {
                this.$confirm(`是否删除 ${row.fileName} 的信息`, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        this.tableLoading = true;
                        dataImportAPI.deleteData(row.importID).then((res) => {
                            if (!res) {
                                this.tableLoading = false;
                                this.$message({ type: "warning", message: "删除失败!" });
                            } else {
                                this.tableLoading = false;
                                this.$message({ type: "success", message: "删除成功!" });
                                this.getData();
                            }
                        }).catch(err => {
                            this.tableLoading = false;
                        });
                    })
                    .catch(() => { });
            },
            selectFile(file, fileList) {
                var format = file.name.replace(/.+\./, "");  //获取文件后缀名
                if (format === 'tdmpack') {  //限制导入文件格式
                    this.$refs.UpLoad.submit(); // 调用手动上传方法
                } else {
                    this.$message({ type: 'warning', message: '文件格式不正确' });
                    this.$refs.UpLoad.clearFiles();
                }
            },
            fileUpload(row) {
                var file = row.file;
                var obj = {
                    "name": file.name,
                };
                var form = new FormData();
                form.append('filename', file);
                //form.append('proID', '10003');
                var imageUpload = params => {
                    return axios.post(this.uploadUrl + JSON.stringify(obj), params, {
                        headers: { 'content-type': 'multipart/form-data', 'Authorization': sessionStorage.getItem('token') }
                    })
                }
                this.loadingFullScreen = this.$loading({
                    lock: true,
                    text: '正在上传文件',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0)'
                });
                imageUpload(form).then(async (res) => {
                    this.loadingFullScreen.close();
                    this.$message({ type: 'success', message: '文件上传成功' });
                    this.$refs.UpLoad.clearFiles();
                    this.getData();
                }).catch(async (err) => {
                    this.loadingFullScreen.close();
                    this.$refs.UpLoad.clearFiles();
                    this.$message({
                        type: 'error', message: err.response.data, center: true, duration: 0, showClose: true
                    });
                    this.getData();
                })
            },
            analysisFile(row) {
                this.selectRow = row;
                this.showSelect = true;
                console.log(this.optionType);
            },
            starAnalysis(row) {
                //if (row.isImport !== true) {
                var params = { importid: row.importID, isDelete: false };
                this.loadingFullScreen = this.$loading({
                    lock: true,
                    text: '正在导入文件',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0)'
                });
                dataImportAPI.importData(params).then(res => {
                    this.loadingFullScreen.close();
                    this.$message({ type: 'success', message: '导入完成' });
                    this.showSelect = false;
                    this.getData();
                }).catch(err => {
                    this.loadingFullScreen.close();
                });
            },
            // 拆分工程单
            splitEngOrder(row) {
                this.loadingFullScreen = this.$loading({ lock: true, text: `正在拆分工程单`, spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0)' });
                this.starSplit(row)
            },
            starSplit(row) {
                if (row.isImport !== true) {
                    projectFileAPI.SplitEngOrder({ PFileID: row.pFileID }).then(res => {
                        if (!!res.exception) {
                            this.loadingFullScreen.close();
                            this.$message({ type: 'error', message: res.resultProcess.error });
                        } else {
                            if (res.isCompleted) {
                                this.loadingFullScreen.setText('正在拆分工程单  ' + '100%')
                                setTimeout(() => {
                                    this.loadingFullScreen.close();
                                    this.$message({ type: 'success', message: '拆分完成' });
                                    this.$emit('change', null);
                                }, 500);
                            } else {
                                setTimeout(() => {
                                    if (res.resultProcess.percent < 100) {
                                        this.loadingFullScreen.setText('正在拆分工程单  ' + res.resultProcess.percent + '%')
                                    } else {
                                        this.loadingFullScreen.setText('正在拆分工程单  ' + '99%')
                                    };
                                    this.starSplit(row)
                                }, 1000);
                            }
                        };
                    }).catch(err => {
                        this.loadingFullScreen.close();
                    });
                }
            },



            downLoadFile() {
                var loadingFullScreen = this.$loading({
                    lock: true,
                    text: '正在下载文件',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.3)'
                });
                var data = {
                    queryPara: this.searchShipName,
                    sModelID: this.childData.parentID ? this.childData.sModelID : null,
                    sTypeID: this.childData.parentID ? null : this.childData.sTypeID,
                    isRetire: this.shipState,
                    deliveryUnit1: this.deliveryUnit[0],
                    deliveryUnit2: this.deliveryUnit[1],
                    deliveryUnit3: this.deliveryUnit[2],
                };
                var isStar = this.securityLevel > 1 ? '★' : '';
                var security = currencyJson.mjOptionsInfo.find(e => e.value === Number(this.securityLevel)).label;
                var fileName = '实力表' + '-' + security + isStar + securityPeriod + '.xlsx';
                dataImportAPI.exportShipList(data).then(res => {
                    loadingFullScreen.close();
                    const blob = new Blob([res], { type: 'application/xlsx;charset=utf-8' });
                    if ('download' in document.createElement('a')) {
                        // 非IE下载
                        const elink = document.createElement('a');
                        elink.download = fileName;
                        elink.style.display = 'none';
                        elink.href = URL.createObjectURL(blob);
                        document.body.appendChild(elink);
                        elink.click();
                        URL.revokeObjectURL(elink.href);
                        document.body.removeChild(elink);
                    } else {
                        // IE10+下载
                        navigator.msSaveBlob(blob, fileName);
                    };
                    this.selectMj = false;
                    this.securityLevel = null;
                    this.securityPeriod = 0;
                }).catch(() => {
                    loadingFullScreen.close();
                });
            },
            handlePageChange({ currentPage, pageSize }) {
                this.tablePage.currentPage = currentPage;
                this.tablePage.pageSize = pageSize;
                this.getData();
            },
            checkboxChange() {
                this.selectedItems = this.$refs.xGrid.getCheckboxRecords();
            },
            checkboxAll() {
                this.selectedItems = this.$refs.xGrid.getCheckboxRecords(true);
            },
            toDate(date) {
                return date ? moment(date).format('YYYY-MM-DD') : '';
            },
        },
        template: "#template"
    }
</script>

<style>
</style>